<template>
  <a-upload
    v-model:file-list="fileList"
    name="avatar"
    list-type="picture-card"
    class="avatar-uploader"
    :data="uploadData"
    :headers="myHeader"
    :show-upload-list="false"
    :action="uploadUrl"
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <img class="user-avatar-img" v-if="avatarUrl" :src="cdnUrl + avatarUrl" alt="avatar" />
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
      <div class="ant-upload-text">Upload</div>
    </div>
  </a-upload>
  <span>{{ t('org.user.userAvatartips') }}</span>
</template>
<script lang="ts">
import { defineComponent, ref, toRefs } from 'vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { FileItem, FileInfo } from '/@/_types/file/index'
import { TOKEN_KEY, getAccessToken } from '/@/kit/token-kit'
import { antUploadChange, beforeImage } from '/@/kit/upload-kit'
import { cdnUrl } from '/@/api/core/upload'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'
import { SUCCESS_CODE } from '/@/framework/profile/code'
const uploadUrl = '/api/org/user/uploadAvatar'
export default defineComponent({
  components: {
    LoadingOutlined,
    PlusOutlined,
  },
  props: {
    avatarUrl: String,
    userId: String,
  },
  emits: ['uploadAvatarSuccess'],
  setup(props, { emit }) {
    const { t } = useI18n()
    const fileList = ref([])
    const loading = ref<boolean>(false)
    const imageUrl = ref<string>('')
    const uploadData = { userId: props.userId }
    const myHeader = { [TOKEN_KEY]: getAccessToken() }

    const handleChange = (info: FileInfo) => {
      antUploadChange(info, {
        uploading: () => (loading.value = true),
        done: () => {
          loading.value = false
          //
          if (info.file.response.code == SUCCESS_CODE) {
            emit('uploadAvatarSuccess', info)
          } else {
            message.error(info.file.response.msg + ' ' + info.file.response.data)
          }
        },
        error: () => {
          loading.value = false
        },
      })
    }

    const beforeUpload = (file: FileItem) => beforeImage(file)

    return {
      t,
      ...toRefs(props),
      fileList,
      loading,
      imageUrl,
      uploadUrl,
      cdnUrl,
      uploadData,
      myHeader,
      handleChange,
      beforeUpload,
    }
  },
})
</script>
<style lang="less" scoped>
.avatar-uploader > ::v-deep(.ant-upload) {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card ::v-deep(.ant-upload-text) {
  margin-top: 8px;
  color: #666;
}

.user-avatar-img {
  width: 126px;
  height: 126px;
}
</style>
